package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.OmcSetMealMapper;
import com.csun.cmny.provider.dao.OmcSetMealItemMapper;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.domain.OmcExpenseItem;
import com.csun.cmny.provider.model.domain.OmcExpenseType;
import com.csun.cmny.provider.model.domain.OmcSetMeal;
import com.csun.cmny.provider.model.domain.OmcSetMealItem;
import com.csun.cmny.provider.model.vo.SetMealItemVo;
import com.csun.cmny.provider.model.vo.SetMealVo;
import com.csun.cmny.provider.service.OmcExpenseItemService;
import com.csun.cmny.provider.service.OmcExpenseTypeService;
import com.csun.cmny.provider.service.OmcSetMealItemService;
import com.csun.cmny.provider.service.OmcSetMealService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Service
@Slf4j
@Transactional
public class OmcSetMealServiceImpl extends BaseService<OmcSetMeal> implements OmcSetMealService {

    @Resource
    private OmcSetMealMapper omcSetMealMapper;

    @Resource
    private OmcSetMealItemService omcSetMealItemService;

    @Resource
    private OmcExpenseItemService omcExpenseItemService;

    @Override
    public Integer saveSetMeal(OmcSetMeal omcSetMeal, LoginAuthDto loginAuthDto) {

        //放入操作者信息
        omcSetMeal.setGroupId(loginAuthDto.getGroupId());
        omcSetMeal.setUpdateInfo(loginAuthDto);

        //同名校验
        if(!checkName(omcSetMeal)){
            throw new OmcBizException(ErrorCodeEnum.OMC10037005);
        }

        //新增
        if(omcSetMeal.isNew()){
            //套餐为初始状态
            omcSetMeal.setStatus(0);
            //插入套餐信息
            int ret = omcSetMealMapper.insertSelective(omcSetMeal);
            //获取套餐项目
            List<OmcSetMealItem> omcSetMealItemList = omcSetMeal.getSetMealItemList();
            //获取套餐Id
            Long setMealId = omcSetMeal.getId();
            //将套餐id、操作者信息放入套餐项目
            if(omcSetMealItemList.size() > 0){

                List<Long> idList = new LinkedList<>();
                for(OmcSetMealItem item : omcSetMealItemList){
                    idList.add(item.getExpenseItemId());
                }

                //查询选择的消费项目
                List<OmcExpenseItem> itemList = omcExpenseItemService.selectByIdList(idList);

                //拷贝属性值
                for(OmcExpenseItem expenseItem : itemList){
                    for(OmcSetMealItem setMealItem : omcSetMealItemList){
                        if(expenseItem.getId().equals(setMealItem.getExpenseItemId())){
                            setMealItem.setSetmealId(setMealId);
                            setMealItem.setCostType(expenseItem.getCostType());
                            setMealItem.setChargeStandard(expenseItem.getChargeStandard());
                            setMealItem.setExpenseTypeName(expenseItem.getExpenseTypeName());
                            setMealItem.setExpenseItemName(expenseItem.getItemName());
                            setMealItem.setGroupId(loginAuthDto.getGroupId());
                            setMealItem.setUpdateInfo(loginAuthDto);
                            setMealItem.setContent(expenseItem.getContent());
                        }
                    }
                }
                //插入套餐项目
                int batchSave = omcSetMealItemService.batchSave(omcSetMealItemList);
                //消费项目使用次数+1
//                int count = omcExpenseItemService.addUsedTimes(idList);
            }
            return ret;
        //修改
        }else {
            //获取套餐Id
            Long setMealId = omcSetMeal.getId();

            //校验套餐启用状态
            OmcSetMeal omcSetMealQuery = selectByKey(setMealId);

            //status: 0-初始状态（可进行修改、删除，不能购买） 1-上架状态（可够买、不可修改） 2-下架状态（可修改、不可删除）
            if(omcSetMealQuery.getStatus().equals(1)){
                throw new OmcBizException(ErrorCodeEnum.OMC10037006);
            }

            //查询原本的套餐消费项目
            OmcSetMealItem omcSetMealItemDelete = new OmcSetMealItem();
            omcSetMealItemDelete.setSetmealId(setMealId);
            int ret = omcSetMealItemService.delete(omcSetMealItemDelete);
//            List<OmcSetMealItem> setMealItemList = omcSetMealItemService.select(omcSetMealItemDelete);
//            使用次数-1
//            if(subUsedTimes.size() > 0){
//                //取得要删除的消费项目的id
//                List<Long> idList = new LinkedList<>();
//                for(OmcSetMealItem item : subUsedTimes){
//                    idList.add(item.getExpenseItemId());
//                }
//                int subRet = omcExpenseItemService.subUsedTimes(idList);
//            }

            //获取套餐项目
            List<OmcSetMealItem> omcSetMealItemList = omcSetMeal.getSetMealItemList();

            //将套餐id、操作者信息放入套餐项目
            List<Long> idList = new LinkedList<>();
            for(OmcSetMealItem item : omcSetMealItemList){
                idList.add(item.getExpenseItemId());
            }

            //查询选择的消费项目
            List<OmcExpenseItem> itemList = omcExpenseItemService.selectByIdList(idList);

            //拷贝属性值
            for(OmcExpenseItem expenseItem : itemList){
                for(OmcSetMealItem setMealItem : omcSetMealItemList){
                    if(expenseItem.getId().equals(setMealItem.getExpenseItemId())){
                        setMealItem.setSetmealId(setMealId);
                        setMealItem.setCostType(expenseItem.getCostType());
                        setMealItem.setChargeStandard(expenseItem.getChargeStandard());
                        setMealItem.setExpenseTypeName(expenseItem.getExpenseTypeName());
                        setMealItem.setExpenseItemName(expenseItem.getItemName());
                        setMealItem.setGroupId(loginAuthDto.getGroupId());
                        setMealItem.setUpdateInfo(loginAuthDto);
                        setMealItem.setContent(expenseItem.getContent());
                    }
                }
            }
            //插入套餐项目
            int retBatch = omcSetMealItemService.batchSave(omcSetMealItemList);
                //消费项目使用次数+1
//                int count = omcExpenseItemService.addUsedTimes(idList);
            return omcSetMealMapper.updateByPrimaryKeySelective(omcSetMeal);
        }
    }

    @Override
    public PageInfo queryListWithPage(OmcSetMeal omcSetMealQuery) {
        PageHelper.startPage(omcSetMealQuery.getPageNum(), omcSetMealQuery.getPageSize());
        List<SetMealVo> setMealVoList = omcSetMealMapper.queryListWithPage(omcSetMealQuery);
        return new PageInfo<>(setMealVoList);
    }

    @Override
    public SetMealVo getById(Long setMealId) {

        //查询套餐
        OmcSetMeal omcSetMeal = selectByKey(setMealId);
        if(omcSetMeal == null){
            throw new OmcBizException(ErrorCodeEnum.OMC10037007);
        }
        SetMealVo setMealVo = new SetMealVo();
        BeanUtils.copyProperties(omcSetMeal,setMealVo);

        //查询套餐项目
        List<SetMealItemVo> setMealItemVoList = omcSetMealItemService.queryBySetMealId(setMealId);

        //放入套餐
        setMealVo.setSetMealItemVoList(setMealItemVoList);
        return setMealVo;
    }

    @Override
    public Integer setReturnStandard(OmcSetMeal omcSetMealQuery) {

        //校验套餐启用状态
        OmcSetMeal omcSetMeal = selectByKey(omcSetMealQuery.getId());
        if(omcSetMeal != null){
            //status: 0-初始状态（可进行修改、删除，不能购买） 1-上架状态（可够买、不可修改） 2-下架状态（可修改、不可删除）
            if(omcSetMeal.getStatus().equals(1)){
                throw new OmcBizException(ErrorCodeEnum.OMC10037006);
            }
            //校验套餐项目是否属于该套餐
            List<OmcSetMealItem> omcSetMealItemList = omcSetMealQuery.getSetMealItemList();
            if(omcSetMealItemList != null && omcSetMealItemList.size() > 0){
                for(OmcSetMealItem item : omcSetMealItemList){
                    OmcSetMealItem omcSetMealItem = omcSetMealItemService.selectByKey(item.getId());
                    if(!omcSetMealItem.getSetmealId().equals(omcSetMeal.getId())){
                        throw new OmcBizException(ErrorCodeEnum.OMC10037008);
                    }
                }
                int ret = omcSetMealItemService.setItemReturnStandard(omcSetMealItemList);
                return ret;
            }
        }
        return 0;
    }

    @Override
    public Integer changeStatus(Long setMealId) {

        //查询套餐
        OmcSetMeal omcSetMeal = selectByKey(setMealId);
        int status = omcSetMeal.getStatus();

        //status: 0-初始状态（可进行修改、删除，不能购买） 1-上架状态（可够买、不可修改） 2-下架状态（可修改、不可删除）
        switch (status){
            case 0:
                //校验套餐退费标准是否设置
                checkIsSetReturnStandard(setMealId);
                omcSetMeal.setStatus(1);
                break;
            case 1:
                omcSetMeal.setStatus(2);
                break;
            case 2:
                omcSetMeal.setStatus(1);
                checkIsSetReturnStandard(setMealId);
                break;
        }
        return omcSetMealMapper.updateByPrimaryKeySelective(omcSetMeal);
    }

    @Override
    public Integer deleteById(Long setMealId) {

        //校验套餐启用状态
        OmcSetMeal omcSetMealQuery = selectByKey(setMealId);

        //status: 0-初始状态（可进行修改，不能购买） 1-上架状态（可够买、不可修改） 2-下架状态（不可购买、不可修改）
        if(!omcSetMealQuery.getStatus().equals(0)){
            throw new OmcBizException(ErrorCodeEnum.OMC10037027);
        }

        //删除原本的消费项目
        OmcSetMealItem omcSetMealItemDelete = new OmcSetMealItem();
        omcSetMealItemDelete.setSetmealId(setMealId);
        //查询要删除的消费项目
        List<OmcSetMealItem> subUsedTimes = omcSetMealItemService.select(omcSetMealItemDelete);
        //使用次数-1
        if(subUsedTimes.size() > 0){
            //取得要删除的消费项目的id
            List<Long> idList = new LinkedList<>();
            for(OmcSetMealItem item : subUsedTimes){
                idList.add(item.getExpenseItemId());
            }
            int subRet = omcExpenseItemService.subUsedTimes(idList);
        }
        //删除套餐项目
        int ret = omcSetMealItemService.delete(omcSetMealItemDelete);

        //删除套餐
        return omcSetMealMapper.deleteByPrimaryKey(setMealId);
    }

    @Override
    public List<OmcSetMeal> queryAll(OmcSetMeal omcSetMeal) {

        List<OmcSetMeal> omcSetMealList = select(omcSetMeal);

        if(omcSetMealList != null || omcSetMealList.size() >0){
            for(OmcSetMeal item : omcSetMealList){
                OmcSetMealItem setMealItemQuery = new OmcSetMealItem();
                setMealItemQuery.setSetmealId(item.getId());
                item.setSetMealItemList(omcSetMealItemService.select(setMealItemQuery));
            }
        }
        return omcSetMealList;
    }

    //同名校验
    public boolean checkName(OmcSetMeal omcSetMeal){
        Example example = new Example(OmcSetMeal.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name",omcSetMeal.getName());
        criteria.andEqualTo("groupId",omcSetMeal.getGroupId());
        if(omcSetMeal.getId() != null && omcSetMeal.getId() != 0){
            criteria.andNotEqualTo("id",omcSetMeal.getId());
        }
        int result = selectCountByExample(example);
        return result<1;
    }

    //校验套餐的退费标准是否设置
    public void checkIsSetReturnStandard(Long setMealId){
        OmcSetMealItem setMealItem = new OmcSetMealItem();
        setMealItem.setSetmealId(setMealId);
        List<OmcSetMealItem> setMealItemList = omcSetMealItemService.select(setMealItem);
        for(OmcSetMealItem omc : setMealItemList){
            if(omc.getReturnStandard() == null){
                throw new OmcBizException(ErrorCodeEnum.OMC10037026);
            }
        }
    }
}
